<?php
namespace S\Util;

use S\Request;

/**
 * dataTable工具类
 */
class DataTable {

    public static function dealTable(){
        $draw = intval(Request::request('draw'));
        if($draw){
            $ret['draw'] = $draw;
            $ret['search'] = self::dealSearch();
            $ret['order'] = self::dealOrder();
            $ret['limit'] = self::dealPager();
        }else{
            $ret = array();
        }

        return $ret;
    }

    protected static function dealSearch(){
        $params = array();

        $columns = Request::request("columns") ? : array();
        foreach($columns as $column){
            $column_name = strip_tags($column['data']);
            $able = strip_tags($column['searchable']);
            $search = strip_tags($column['search']['value']);

            if(isset($search) && $search !== "" && $able){
                $params[$column_name] = $search;
            }
        }

        return $params;
    }

    protected static function dealPager(){
        $start = intval(Request::request('start'));
        $length = intval(Request::request('length'));

        return array($start, $length);
    }

    protected static function dealOrder(){
        $orders = array();
        $order_columns = Request::request("order") ? : array();
        $columns = Request::request("columns") ? : array();

        foreach($order_columns as $order_column){
            $column_number = strip_tags($order_column['column']);
            $column_name = strip_tags($columns[$column_number]['data']);
            $able = strip_tags($columns[$column_number]['orderable']);
            $order = strip_tags($order_column['dir']);

            if($able&&$order){
                $orders[$column_name] = $order;
            }
        }

        return $orders;
    }
}
